package mobi.hami.huapin.core.stock;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import mobi.hami.huapin.core.RestTemplateHelper;
import mobi.hami.huapin.dto.SkuStockDTO;
import mobi.hami.huapin.dto.StockSubDTO;
import mobi.hami.huapin.model.UserOrderDetail;
import mobi.hami.huapin.service.impl.ProductForeEndServiceImpl;
import mobi.hami.huapin.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类说明
 *
 * @author 阿飞 jijunjian@hami.mobi
 * @date 2018-10-18 20:30
 */
@Component
public class StockUtil {

    private static final Logger logger = LoggerFactory.getLogger(StockUtil.class);
    private static  final String WMS_DOMAIN = "https://hmall228.hami.mobi/wms/";
    private static final  String DEFAULT_WAREHOURSE_ID = "101024";

    @Autowired
    private RestTemplateHelper restTemplateHelper;

    /**
     * 批量查询库存  warehouse_id 没有就用默认的
     * @param ids
     * @param warehouse_id
     * @return
     */
    public  List<SkuStockDTO> queryBat(String ids,String warehouse_id)
    {
        String url = WMS_DOMAIN+"wms/stock/querybat.do";
        JSONObject notifyparams = new JSONObject();
        notifyparams.put("sku_ids",ids);
        notifyparams.put("warehouse_id", (warehouse_id.length() == 0 ?DEFAULT_WAREHOURSE_ID : warehouse_id));

        String notifyresult = restTemplateHelper.postForObject(url, notifyparams.toJSONString());

        logger.info("StockUtil.queryBat->"+notifyresult+" ->"+ ids);


        JSONObject notiyres = JSONObject.parseObject(notifyresult);

        //List<SkuStockDTO> stockDTOS = JSON.parseArray(notifyresult, new TypeReference<SkuStockDTO>() {});

        List<SkuStockDTO> stockDTOS = JSON.parseObject(notiyres.getString("data"), new TypeReference<ArrayList<SkuStockDTO>>() {});

        return  stockDTOS;
    }

    /**
     *如果返回 0表示正常，否则表示库存不了足商品编号
     * @param kus
     * @param order_code
     * @param warehouse_id
     * @return
     */
    public  String subBat(List<UserOrderDetail> kus, String order_code, String warehouse_id)
    {
        String url = WMS_DOMAIN+"wms/stock/subbatstock.do";
        JSONObject notifyparams = new JSONObject();

        List<StockSubDTO> stockSubDTOS = new ArrayList<>();

        kus.forEach(a->{

            StockSubDTO item = new StockSubDTO();
            item.setSkuid(a.getSku_id());
            item.setSub_count(a.getSku_cout());

            stockSubDTOS.add(item);

        });


        notifyparams.put("order_code",order_code);
        notifyparams.put("warehouse_id", (warehouse_id.length() == 0 ?DEFAULT_WAREHOURSE_ID : warehouse_id));
        notifyparams.put("list",stockSubDTOS);

        String notifyresult = restTemplateHelper.postForObject(url, notifyparams.toJSONString());

        logger.info("StockUtil.subBat->"+notifyresult+" ->"+ notifyparams.toJSONString());

        JSONObject notiyres = JSONObject.parseObject(notifyresult);
        if (  notiyres.get("success").toString().equals("false") )
        {
            return  notiyres.get("msg").toString();
        }
        else
        {
            return  "0";
        }
    }



    /**
     * 赠送惊喜小礼品暂扣库存
     * @param orderId
     * @param skuId
     * @param skuCount
     */
    public void addRepertoryBySkuInfo(String orderId,Integer skuId,Integer skuCount){
        //https://hmall228.hami.mobi/wms/wms/stock/subonestock.do
        Map<String,Object> paramMap= new HashMap<>();
        paramMap.put("orderid",orderId);
        paramMap.put("skuid",skuId);
        paramMap.put("sub_count",skuCount);
        paramMap.put("warehouse_id","101024");

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");

        try {
            HttpUtil.post( WMS_DOMAIN+"wms/stock/subonestock.do", JSONUtils.toJSONString(paramMap), headers);
        } catch (Exception ex) {
            logger.error("调用扣库存出现异常：" + ex.getMessage());
        }
    }


    /**
     * 实际库存处理
     * @param orderCode
     */
    public void actualRepertoryByOrderCode(String orderCode,String path){
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");
        Map<String,Object> paramMap= new HashMap<>();
        paramMap.put("orderCode",orderCode);
        paramMap.put("warehouse_id","101024");
        try {
            HttpUtil.post( WMS_DOMAIN+path, JSONUtils.toJSONString(paramMap), headers);
        } catch (Exception ex) {
            logger.error("调用库存出现异常：" + ex.getMessage()+"Path:"+path);
        }
    }
}
